<!--  -->
<template>
  <div class='login_container'>
    <!-- title:对话框左上角的标题 v-model:控制对话框显示与隐藏 -->
    <el-dialog v-model="useStore.visiable" title="用户登录" ref="dialog">
        <!-- 对话框身体部分结构 -->
        <el-row>
            <!-- 左侧解构：手机号码登录、微信扫一扫登录 -->
            <el-col :span="12">
                <div class="login">
                  <div v-show="scene==0">
                       <el-form :model="loginParam" :rules="rules" ref="form">
                        <el-form-item prop="phone">
                            <el-input :placeholder="$t('login.phone')" :prefix-icon="User" v-model="loginParam.phone"></el-input>
                        </el-form-item>
                        <el-form-item  prop="code">
                            <el-input :placeholder="$t('login.verification')" :prefix-icon="Lock" v-model="loginParam.code"></el-input>
                        </el-form-item>
                         <el-form-item>
                            <el-button :disabled="!isPhone||flag ?true:false">
                                <CountDown v-if="flag" :flag="flag" @getFlag="getFlag"/>
                                <span v-else @click="getCode">{{$t('login.getVerification')}}</span>
                            </el-button>
                        </el-form-item>
                    </el-form>
                      <el-button style="width:100%" type="primary" size="default" :disabled="!isPhone||loginParam.code.length<6?true:false" @click="login">{{$t('login.name')}}</el-button>
                    <div class="bottom" @click="changeScene">  
                        <p>{{$t('login.loginByWeixin')}}</p>
                        <svg t="1694534471936" class="icon" viewBox="0 0 1137 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2314" width="16" height="16"><path d="M814.276923 310.153846h9.694675c-32.795266-176.094675-203.512426-310.153846-408.804734-310.153846C186.168047 0 0.454438 166.627219 0.454438 371.881657A347.531361 347.531361 0 0 0 93.046154 606.295858v168.52071l128.302958-74.224852a449.211834 449.211834 0 0 0 193.817752 43.171598c8.028402 0 16.359763-0.378698 24.426035-0.378699a329.997633 329.997633 0 0 1-8.861538-77.254437c-0.530178-196.16568 171.512426-355.976331 383.545562-355.976332z m-261.301775-92.781065a61.91716 61.91716 0 1 1-61.462722 61.727811 61.689941 61.689941 0 0 1 61.614201-61.727811zM276.525444 341.207101a61.91716 61.91716 0 1 1 61.500592-62.106509A61.80355 61.80355 0 0 1 276.639053 341.207101z m537.751479 31.053254c-178.215385 0-322.613018 131.786982-322.613018 294.627219s144.397633 294.627219 322.613018 294.627219a351.053254 351.053254 0 0 0 98.461539-14.011834l131.521893 76.118343v-150.343195a281.183432 281.183432 0 0 0 92.591716-206.390533c-0.189349-162.840237-144.586982-294.627219-322.575148-294.627219z m-92.326627 248.047337a46.579882 46.579882 0 1 1 46.163313-46.579881 46.352663 46.352663 0 0 1-46.163313 46.579881z m214.986982 0a46.579882 46.579882 0 1 1 46.201184-46.579881 46.352663 46.352663 0 0 1-46.201184 46.579881z" fill="#1296db" p-id="2315"></path></svg>
                    </div>
                  </div>
                  <div class="webchat" v-show="scene==1">
                    <!-- 在这个容器当中显示微信扫码登录页面 -->
                    <div id="login_container"></div>
                    <div class="phone" @click="handler">
                        <p>{{$t('login.loginByMessage')}}</p>
                        <svg t="1694844154590" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4266" width="16" height="16"><path d="M709.98223 0H313.653832A181.968961 181.968961 0 0 0 131.684871 181.968961v659.69814a182.575524 182.575524 0 0 0 181.968961 181.968961h396.328398a182.575524 182.575524 0 0 0 181.968961-181.968961V181.968961a181.968961 181.968961 0 0 0-181.968961-181.968961z m100.204241 753.472811H213.813529V181.968961A100.446866 100.446866 0 0 1 313.653832 82.128658h396.328398A100.325554 100.325554 0 0 1 810.186471 181.968961zM213.813529 835.601469h596.372942v6.065632a100.204241 100.204241 0 0 1-100.204241 100.082929H313.653832a100.325554 100.325554 0 0 1-100.204241-100.082929z" fill="#d81e06" p-id="4267"></path><path d="M469.540576 909.116929h84.918848a24.262528 24.262528 0 1 0 0-49.374244h-84.918848a24.262528 24.262528 0 0 0 0 49.374244z" fill="#d81e06" p-id="4268"></path></svg>
                    </div>
                  </div>
                </div>
            </el-col>
            <el-col :span="12">
                <div class="leftContent">
                    <div class="top">
                        <div class="item">
                            <img src="../../assets/images/code_app.png" alt="">
                            <svg t="1694656771285" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4039" width="16" height="16"><path d="M664.250054 368.541681c10.015098 0 19.892049 0.732687 29.67281 1.795902-26.647917-122.810047-159.358451-214.077703-310.826188-214.077703-169.353083 0-308.085774 114.232694-308.085774 259.274068 0 83.708494 46.165436 152.460344 123.281791 205.78483l-30.80868 91.730191 107.688651-53.455469c38.558178 7.53665 69.459978 15.308661 107.924012 15.308661 9.66308 0 19.230993-0.470721 28.752858-1.225921-6.025227-20.36584-9.521864-41.723264-9.521864-63.862493C402.328693 476.632491 517.908058 368.541681 664.250054 368.541681zM498.62897 285.87389c23.200398 0 38.557154 15.120372 38.557154 38.061874 0 22.846334-15.356756 38.156018-38.557154 38.156018-23.107277 0-46.260603-15.309684-46.260603-38.156018C452.368366 300.994262 475.522716 285.87389 498.62897 285.87389zM283.016307 362.090758c-23.107277 0-46.402843-15.309684-46.402843-38.156018 0-22.941502 23.295566-38.061874 46.402843-38.061874 23.081695 0 38.46301 15.120372 38.46301 38.061874C321.479317 346.782098 306.098002 362.090758 283.016307 362.090758zM945.448458 606.151333c0-121.888048-123.258255-221.236753-261.683954-221.236753-146.57838 0-262.015505 99.348706-262.015505 221.236753 0 122.06508 115.437126 221.200938 262.015505 221.200938 30.66644 0 61.617359-7.609305 92.423993-15.262612l84.513836 45.786813-23.178909-76.17082C899.379213 735.776599 945.448458 674.90216 945.448458 606.151333zM598.803483 567.994292c-15.332197 0-30.807656-15.096836-30.807656-30.501688 0-15.190981 15.47546-30.477129 30.807656-30.477129 23.295566 0 38.558178 15.286148 38.558178 30.477129C637.361661 552.897456 622.099049 567.994292 598.803483 567.994292zM768.25071 567.994292c-15.213493 0-30.594809-15.096836-30.594809-30.501688 0-15.190981 15.381315-30.477129 30.594809-30.477129 23.107277 0 38.558178 15.286148 38.558178 30.477129C806.808888 552.897456 791.357987 567.994292 768.25071 567.994292z" fill="#5D5D5D" p-id="4040"></path></svg>
                            <p>{{$t('login.loginByScanCode')}}</p>
                            <p>{{$t('login.quickAppReg')}}</p>
                        </div>
                        <div class="item">
                            <img src="../../assets/images/code_login_wechat.png" alt="">
                            <svg t="1694656849627" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5196" width="16" height="16"><path d="M820.409449 797.228346q0 25.19685-10.07874 46.866142t-27.716535 38.299213-41.322835 26.204724-50.897638 9.574803l-357.795276 0q-27.212598 0-50.897638-9.574803t-41.322835-26.204724-27.716535-38.299213-10.07874-46.866142l0-675.275591q0-25.19685 10.07874-47.370079t27.716535-38.80315 41.322835-26.204724 50.897638-9.574803l357.795276 0q27.212598 0 50.897638 9.574803t41.322835 26.204724 27.716535 38.80315 10.07874 47.370079l0 675.275591zM738.771654 170.330709l-455.559055 0 0 577.511811 455.559055 0 0-577.511811zM510.992126 776.062992q-21.165354 0-36.787402 15.11811t-15.622047 37.291339q0 21.165354 15.622047 36.787402t36.787402 15.622047q22.173228 0 37.291339-15.622047t15.11811-36.787402q0-22.173228-15.11811-37.291339t-37.291339-15.11811zM591.622047 84.661417q0-8.062992-5.03937-12.598425t-11.086614-4.535433l-128 0q-5.03937 0-10.582677 4.535433t-5.543307 12.598425 5.03937 12.598425 11.086614 4.535433l128 0q6.047244 0 11.086614-4.535433t5.03937-12.598425z" p-id="5197"></path></svg>
                            <p>{{$t('login.loginByScanCode')}}</p>
                            <p>{{$t('login.app')}}APP</p>
                        </div>                       
                    </div>
                     <p class="tip">{{$t('login.OffDesplaHos')}}</p>
                     <p class="tip">{{$t('login.quickRegSaf')}}</p>
                </div>
            </el-col>
        </el-row>
        <template #footer>
            <el-button type="primary" size="default" @close="closeDialog">{{$t('login.closeWindow')}}</el-button>
        </template>
  </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import { ref,reactive,computed,watch} from 'vue'
import { User,Lock } from '@element-plus/icons-vue'
// 获取user仓库的数据（visiable)可以控制login组件的对话框显示与隐藏
import useUserStore from '@/store/modules/user';
// 引入倒计时组件
import CountDown from '../countdown/index.vue'
import {ElMessage} from "element-plus";
// 引入wx扫码登录参数请求
import {reqWxLogin} from '@/api/hospital/index'
import type {WXLoginResponseData} from '@/api/hospital/type'
import {useRouter,useRoute} from 'vue-router';

let useStore=useUserStore();
// 获取路由器对象
let $router=useRouter();
let $route=useRoute()
let scene=ref<number>(0);//0代表手机号码登录  如果是1 微信扫码登录
// 定义一个相应式数据（visiable）可以控制login组件的对话框显示与隐藏
let flag=ref<boolean>(false);//false如果为真，开启倒计时 flag:为假的并非倒计时
// 获取form组件实例
let form=ref<any>()

// 收集表单数据---手机号码
let loginParam=reactive({
    phone:'',//手机手机号码
    code:'',//收集验证码
})

// 计算出当前表单元素收集的内容是否是手机号码格式
let isPhone=computed(()=>{
    // 手机号码正则表达式
    const reg=/^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/;
    // 返回布尔值：真代表手机号码、假代表的即为不是手机号码
    return reg.test(loginParam.phone);
})


// 生成微信扫码登录|微信小图标切换为微信扫码登录
const changeScene=async()=>{
        // 切换场景为1
        scene.value=1;
        // 发请求获取微信扫码二维码需要参数
        // 咋们在向服务器发请求，获取微信扫码登录页面参数
        // 还需要携带一个参数：告诉学校服务器用户授权成功以后重定向项目某一个页面
        let redirect_URL=encodeURIComponent(window.location.origin+'/wxlogin');
        console.log(redirect_URL);
        let result:WXLoginResponseData=await reqWxLogin(redirect_URL);
       console.log(result);
       
        
        // 生成微信扫码登录二维码页面
        // @ts-ignore 
        new WxLogin({
            self_redirect:true,//true:手机点击确认登陆后可以在iframe内跳转到redirect_url
            id:"login_container",//显示二维码容器设置
            appid:result.data.appid,//应用位置标识appid
            scope:"snsapi_login",//当前微信扫码登录页面已经授权了
            redirect_uri:result.data.redirectUri,//填写授权回调域路径，就是用户授权成功以后，微信服务器向公司后台推送code地址
            state:result.data.state,//state就是学校服务器重定向的地址携带用户信息
            style:"black",
            href:"",
        });
 };


// 获取验证码按钮的回调
const getCode=async()=>{
    // 解决element-plus按钮禁用还能点击的问题
    if(!isPhone.value||flag.value)return;
    // 开启倒计时模式，倒计时组件显示出来
    flag.value=true;
     // 通知pinia仓库存储验证码
   try {
        // 获取验证码成功
        await useStore.getCode(loginParam.phone);
        // console.log('组件result',useStore.code);
        loginParam.code=useStore.code;
   } catch (error) {
    // 获取验证码失败
    ElMessage({
        type:"error",
        message:(error as Error).message,
    })
   }
};
// 计数器子组件绑定的自定义事件
// 当倒计时为零的时候，通知父组件倒计时组件隐藏
const getFlag=(val:boolean)=>{
    // console.log(val);
    // 倒计时模式结束
    flag.value=val;
}

// 点击用户登录按钮回调
const login=async()=>{
    // 保证表单校验两项都符合条件
    await form.value.validate();    
    // alert(123)
    // 发起登录请求
    // 登录请求成功：顶部组件需要展示用户名字、对话框关闭
    // 登录请求失败：弹出对应登录失败的错误信息
    try {
        if(loginParam.code===useStore.code){
            // 用户登录成功
            await useStore.userLogin(loginParam);
            // 关闭对话框
            useStore.visiable=false;
            // 获取url的query参数
            let redirect=$route.redirect;
            if(redirect){
                $router.push(redirect as string);
            }else{
                $router.push('/home');
            }
        }else{
            alert('验证码输入错误,请重新输入');
            loginParam.code=""
           login();
        } 
    } catch (error) {
        ElMessage({
            type:'error',
            message:(error as Error).message,
        })
    }
}
// 自定义校验规则：手机号码自定义校验规则
const validatorPhone=(rule:any,value:any,callBack:any)=>{
    // rule:即为表单校验规则对象
    // value:即为当前文本的内容
    // callBack:回调函数
        const reg=/^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/;
        if(reg.test(value)){
        callBack();
        }else{
        callBack(new Error('请输入正确的手机号码格式'));
        }

}
// 验证码自定义校验规则
const validatorCode=(rule:any,value:any,callBack:any)=>{
    // rule:即为表单校验规则对象
    // value:即为当前文本的内容
    // callBack:回调函数
    if(/^\d{6}$/.test(value)){
        callBack();
    }else{
        callBack(new Error("请输入正确的验证码格式"));
    }
}
// 表单校验的规则对象
const rules={
    // 手机号码校验规则
    // required:代表的校验错误的提示信息
    // message:代表的校验错误的提示信息
    // trigger:代表表单校验触发的时机 change:文本发生变化时候进行校验
    // min:代表的是最小位数
    // max:代表的是最大的位置
    // 传统的校验规则
    // phone:[{required:true,message:"手机号码务必11位",trigger:"change",min:11}],
    // code:[{required:true,message:"校验务必6位",trigger:"blue",min:6}],
     phone:[{trigger:"change",validator:validatorPhone}],
    code:[{trigger:"change",validator:validatorCode}],
}

// 关闭窗口按钮的回调
const closeDialog=()=>{
    useStore.visiable=false;
}
// 点击手机短信验证码盒子回调
const handler=()=>{
    scene.value=0;
}
// 监听场景的数据
watch(()=>scene.value,(val:number)=>{
    if(val===1){
        useStore.queryState();
    }
})
</script>
<script lang="ts">
export default {
    name:'Login'
}
</script>
<style scoped lang='scss'>
.login_container{
    ::v-deep(.el-dialog__body){
        border-top:1px solid #ccc;
        border-bottom:1px solid #ccc;
    }
    .login{
        padding:20px;
        border:1px solid #ccc;
        .webchat{
            display: flex;
            flex-direction: column;
            align-items: center;
            .phone{
                display: flex;
                flex-direction: column;
                align-items: center;
                p{
                    margin:10px 0px;
                }
            }
        }
    }
    .bottom{
        display: flex;
        flex-direction: column;
        align-items: center;
        p{
            margin:10px 0px;
        }
    }

    .leftContent{
        .top{
            display: flex;
            justify-content: space-around;
            .item{
                display: flex;
                flex-direction: column;
                align-items:center;
                img{
                    width:130px;
                    height: 130px;
                }
                p{
                    margin: 10px 0px;
                }
            }
        }
    }

    .tip{
        text-align: center;
        margin:20px 0px;
        font-size: 20px;
        font-weight: 900;
    }
}
</style>